# !/usr/bin/python
# -*- coding: UTF-8 -*-
#
# sudo apt-get install libboost-python-dev 
# sudo apt-get install libboost-thread-dev
# sudo apt-get install libbluetooth-dev
# sudo apt-get install libglib2.0-dev
# sudo apt-get install python-dev
# sudo pip install pybluez
# sudo pip install gattlib

#import bluetooth
# from gattlib import DiscoveryService
#from bluetooth.ble import DiscoveryService

#print "blescan start..." 
#nearby_devices = bluetooth.discover_devices(lookup_names = True)
#print "found %d devices" % len(nearby_devices) 

#for addr, name in nearby_devices:
#    print "  %s - %s" % (addr, name)

#service = DiscoveryService()
#devices = service.discover(2)

#for address, name in devices.items():
#    print("name: {}, address: {}".format(name, address))

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
# sudo apt-get install libglib2.0-dev
# sudo pip install bluepy

import os
import sys
import shutil
import datetime
#from time import ctime,sleep
from bluepy.btle import Scanner, DefaultDelegate

class ScanDelegate(DefaultDelegate):
    def __init__(self,whitelist,save = False,sd = True):
        DefaultDelegate.__init__(self)
        self.whitelist = whitelist
        self.save = save
        self.sd = sd

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if self.sd:
            if isNewDev:
                print "Discovered device:", dev.addr,dev.scanData.get(8,"No name")
            elif isNewData:
                if (len(self.whitelist) == 0) or (dev.addr.lower() in (item.lower() for item in self.whitelist)):
                    if self.save:
                        fo = open("../logdata/" + dev.addr.replace(":","_",5)+".txt", "ab")
                        #写入文件时间戳
                        fo.write("time %s " % datetime.datetime.now())
                        #写入文件MAC
                        fo.write("mac %s " % dev.addr)
                        #写入文件信号强度
                        fo.write("rssi %d " % dev.rssi)
                        #写入数据
                        fo.write("data ")
                        
                    print "Received new data from mac", dev.addr,"time",datetime.datetime.now(),"rssi %d" % dev.rssi,"data",
                    
                    for i in map(ord,(dev.scanData[255])):
                        print "%02X " % i,
                        if self.save: 
                            fo.write("%02X " % i)
                    print ""
                    if self.save:
                        fo.write("\r\n")
                        fo.close()
        else:
            print "Discovered device:", dev.addr,dev.scanData.get(8,"No name")

def lescan(hcix,timeout, delegate):
    scanner = Scanner(hcix).withDelegate(delegate)
    devices = scanner.scan(timeout)
    return;

#def ledump(devices,whitelist):
#    for dev in devices:
#        print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
#        for (adtype, desc, value) in dev.getScanData():
#            print "  %s = %s" % (desc, value)
#    return;

def printusage():
    print "Usage:"
    print "     sudo lescan.py lescan/ledump [-h help] [-i hci dev number] [-s Save a file and Remarks] [-t timeout] [-w/-wf whitelist:..../whitelist in file]"
    print "     sudo python lescan.py ledump -i hci0 -s 10_00_no -t 6 -wf ./whitelist.txt"
    return;


if __name__ == '__main__':

    if "-h" in sys.argv:
        printusage()  
        exit()
    if "-t" in sys.argv:
        timeout = int(sys.argv[sys.argv.index("-t") + 1])  
    else:
        timeout = 60      
    if "-w" in sys.argv:
        whitelist = sys.argv[(sys.argv.index("-w") + 1):len(sys.argv)]
    elif "-wf" in sys.argv:
        if (sys.argv.index("-wf") + 1) < len(sys.argv):
            whitelist = []
            testconditionlist = []
            fs = open(sys.argv[(sys.argv.index("-wf") + 1)],"rb")
            lines = fs.readlines()
            fs.close()
            for i in lines:
                if len(i.split()) > 0 and i.split()[0] == '-w':
                    whitelist.append(i.split()[1].lower())
                if len(i.split()) > 2 and i.split()[2] == '-s':
                    testconditionlist.append(i.split()[3].lower())   
            #print whitelist,testconditionlist
        else:
            print "\r\nplese input the whitelist file path\r\n"
            exit() 
        #exit()  
    else:
        whitelist = []  
    if "-i" in sys.argv:
        hcix = int(sys.argv[sys.argv.index("-i") + 1][3:])
    else:
        hcix = 0

    if "-s" in sys.argv:
        saveafile = True
        #删除旧数据文件
        for filename in whitelist:
            filename = "../logdata/" + filename.lower().replace(":","_",5) + ".txt"
            if os.path.exists(filename):
                os.remove(filename)
        #创建新的数据文件
        i = 0
        if not os.path.exists(r'../logdata/'):
            os.makedirs(r'../logdata/')
        for filename in whitelist:
            fo = open("../logdata/" + filename.lower().replace(":","_",5) + ".txt","wb")
            if "-wf" in sys.argv and len(testconditionlist) == len(whitelist):
                fo.write("# power %s\r\n# dist %s\r\n# occl %s\r\n# mac %s\r\n# start_time %s\r\n" % 
                        (testconditionlist[i].split('_')[0],
                         testconditionlist[i].split('_')[1],
                         testconditionlist[i].split('_')[2],# no ,half ,full
                         filename.lower(),
                         datetime.datetime.now()
                         ))
            else:
                fo.write("# power %s\r\n# dist %s\r\n# occl %s\r\n# mac %s\r\n# start_time %s\r\n" % 
                        (sys.argv[(sys.argv.index("-s") + 1)].split('_')[0],
                         sys.argv[(sys.argv.index("-s") + 1)].split('_')[1],
                         sys.argv[(sys.argv.index("-s") + 1)].split('_')[2],# no ,half ,full
                         filename.lower(),
                         datetime.datetime.now()
                         ))
            fo.close()
            i += 1
    else:
        saveafile = False
    #开始扫描
    print "Test start: %s" % datetime.datetime.now()
    
    if "lescan" in sys.argv:
        lescan(hcix,timeout,ScanDelegate(whitelist,saveafile,False))
    
    if "ledump" in sys.argv:
        lescan(hcix,timeout,ScanDelegate(whitelist,saveafile,True))
        
    if saveafile == True: 		
		for filename in whitelist:
			fo = open("../logdata/" + filename.lower().replace(":","_",5) + ".txt","ab")
			fo.write("# stop_time %s\r\n" % datetime.datetime.now())
			fo.close()
	
    if os.path.exists(r'../logdata/'):
        if os.path.exists('../' + sys.argv[(sys.argv.index("-s") + 1)]):
            shutil.rmtree('../' + sys.argv[(sys.argv.index("-s") + 1)])
        os.rename(r'../logdata/','../' + sys.argv[(sys.argv.index("-s") + 1)])
        os.system('sudo chmod -R 777 ' + '../' + sys.argv[(sys.argv.index("-s") + 1)])
    print "Test over: %s" % datetime.datetime.now()#,sys.argv



   
